import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:robot3/services.dart';
import 'package:robot3/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../Robot.dart';
import '../backButton1.dart';
import '../main.dart';
import '../pojo.dart';
import '../viewmodel/huxing_provider.dart';

//户型选择
void main() {
  runApp(MaterialApp(home: const HuxingxuanzheScreen()));
}

class HuxingxuanzheScreen extends StatelessWidget {
  const HuxingxuanzheScreen({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => HuXingProvider(),
      child: _ShangpinkuScreen(title: '1',),
    );
    // );
  }
}

class _ShangpinkuScreen extends StatefulWidget {
  const _ShangpinkuScreen({super.key, required this.title});

  final String title;

  @override
  State<_ShangpinkuScreen> createState() => _PageState();
}

const   fromAndroid = true;

class _PageState extends State<_ShangpinkuScreen> with RouteAware {

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    ///暂时没有使用
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  ///暂时没有使用
  @override
  void didPopNext() {
    super.didPopNext();
    print('123');
  }

  @override
  void dispose() {
    ///暂时没有使用
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  ///获取accessToken
  Future<void> _getParams() async {
    try {
      final String result = await platformMethodChannel.invokeMethod('init');
      print("result:" + result);
      final params = result.split('_');
      final  accessToken = params[0];
      Robot.accessToken = accessToken;

      print("accessToken:" + accessToken);
      final   userId = params[1];
      Robot.userId = userId;
      print("userId:" + userId);
      final  companyId = params[2];
      Robot.companyId = companyId;
      print("companyId:" + companyId);

      final provider = Provider.of<HuXingProvider>(
        context,
        listen: false,
      );

      provider.getDesigners(
        accessToken: Robot.accessToken,
        userId: Robot.userId,
        companyId: Robot.companyId,
      );
      provider.getSysDicByType(
        accessToken: Robot.accessToken,
        type: "HOUSE_TYPE",
      );
      provider.getCustomers();
      provider
          .getHouseLayouts(
        accessToken: Robot.accessToken,
        userId: Robot.userId,
        companyId: Robot.companyId,
      )
          .then((value) {});
    } on PlatformException catch (e) {
      print("Failed to get parameters: '${e.message}'.");
    }
  }

  @override
  void initState() {
    super.initState();

    // 监听来自原生的通知
    platformMethodChannel.setMethodCallHandler((call) async {
        // 当接收到 onResume 的通知时执行逻辑
      if(call.method=="onResume"){
        print("FlutterActivity resumed:"+call.method);
        final provider = Provider.of<HuXingProvider>(context, listen: false);
        provider.a1();

      }
    });

    if(fromAndroid) {
      _getParams();
    }else{
      final provider = Provider.of<HuXingProvider>(context, listen: false);
      login().then((value) {
        if (value) {
          provider.getDesigners(
            accessToken: Robot.accessToken,
            userId: Robot.userId,
            companyId: Robot.companyId,
          );
          provider.getSysDicByType(
            accessToken: Robot.accessToken,
            type: "HOUSE_TYPE",
          );
          provider.getCustomers();
          provider
              .getHouseLayouts(
            accessToken: Robot.accessToken,
            userId: Robot.userId,
            companyId: Robot.companyId,
          )
              .then((value) {});
        }
      });
    }
      }

  @override
  Widget build(BuildContext context) {
    final isLoading = context.watch<HuXingProvider>().isLoading;
    return Scaffold(
        resizeToAvoidBottomInset:false,
        body: GestureDetector(
        onTap: () {
          print('root onTap');
        },
        behavior: HitTestBehavior.translucent,
        // Gesture does not block other gestures
        child: Stack(
          children: [
            // Image equivalent to the Image composable
            Image.asset(
              'images/bg.png', // 替换为你的图片路径
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            ),
            const Padding(
              padding: EdgeInsets.only(
                left: 30 / ratio,
                right: 30 / ratio,
                top: 30 / ratio,
                bottom: 30 / ratio,
              ),
              child: // 加载完成后显示商品信息
                  Content01(child: Content()),
            ),
            Align(alignment: Alignment.bottomCenter, child: BottomBar()),
          if(isLoading)
           Center(child: CircularProgressIndicator(color: Colors.blue),),
          ],
        ),
      ),
    );
  }
}

class Content01 extends StatelessWidget {
  final Widget child;

  const Content01({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [SizedBox(height: 60 / ratio), Expanded(child: child)],
      // ),
    );
  }
}

class Info extends StatefulWidget {
  const Info({super.key});

  @override
  _InfoState createState() => _InfoState();
}

class _InfoState extends State<Info> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController phoneController2 = TextEditingController();
  final TextEditingController nameController = TextEditingController();
  final TextEditingController nameController2 = TextEditingController();

  @override
  void dispose() {
    // Always dispose of controllers when the widget is disposed
    phoneController.dispose();
    nameController.dispose();
    nameController2.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final names = context.watch<HuXingProvider>().names;
    return Consumer<HuXingProvider>(
      builder: (context, provider, child) {
        return Padding(
          padding: EdgeInsets.all(0),
          child: Row(
            children: [
              Column(                spacing: 30 / ratio,
                children: [
                  Row(
                    children: [
                      Text(
                        "户型名称",
                        style: TextStyle(
                          color: MyBlack,
                          fontSize: 24 / ratio,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 20 / ratio),

                      SizedBox(
                        width: 374 / ratio,
                        height: 44 / ratio,
                        child: RobotEditText(
                          controller: phoneController,
                          onTextChanged: (text) {
                            provider.setName(text);
                          },
                        ),
                      ),
                      SizedBox(width: 60 / ratio),
                      Text(
                        "    户型",
                        style: TextStyle(
                          color: MyBlack,
                          fontSize: 24 / ratio,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 20 / ratio),
                      SizedBox(
                        width: 374 / ratio,
                        height: 44 / ratio,
                        child: GestureDetector(
                          onTap: () {
                            print("1");
                          },
                          child: RobotPopupMenuButton2(
                            map: ['全部', ...names],
                            width: 374 / ratio,
                            height: 44 / ratio,
                            itemHeight: 80 / ratio,
                            offsetY: 44 / ratio,
                            onItemSelected: (text) {
                              print(text);
                              provider.setSelectedHouseType(text);
                            },
                            init: provider.selectedHouseType,
                          ),
                        ),
                      ),
                      SizedBox(width: 47 / ratio),
                      ConfirmButton(
                        onClick: (text) {
                          // Navigator.of(context).pushNamed('/http');
                          provider.getHouseLayouts(
                            accessToken: Robot.accessToken,
                            userId: Robot.userId,
                            companyId: Robot.companyId,
                          );
                        },
                        text: "查询",
                        width: 148 / ratio,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "社区地区",
                        style: TextStyle(
                          color: MyBlack,
                          fontSize: 24 / ratio,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 20 / ratio),

                      SizedBox(
                        width: 374 / ratio,
                        height: 44 / ratio,
                        child: RobotEditText(
                          controller: phoneController2,
                          onTextChanged: (text) {},
                        ),
                      ),
                      SizedBox(width: 60 / ratio),
                      Text(
                        "创建者",
                        style: TextStyle(
                          color: MyBlack,
                          fontSize: 24 / ratio,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 20 / ratio),
                      SizedBox(
                        width: 374 / ratio,
                        height: 44 / ratio,
                        child: GestureDetector(
                          onTap: () {
                            print("1");
                          },
                          child: RobotPopupMenuButton2(
                            map: [
                              '全部',
                              ...provider.designers.map(
                                (user) => user.nickname,
                              ),
                            ],
                            // map: provider.designers.map((user) => user.nickname).toList(),
                            width: 374 / ratio,
                            height: 44 / ratio,
                            itemHeight: 80 / ratio,
                            offsetY: 44 / ratio,
                            onItemSelected: (text) {
                              provider.setSelectedDesigner(text);
                              print(text);
                            },
                            init: provider.selectedDesigner,
                          ),
                        ),
                      ),
                      SizedBox(width: 47 / ratio),
                      // SizedBox(width: 30 / ratio),
                      CancelButton(
                        onClick: (text) {
                          provider.reset();
                          phoneController.text = '';
                          phoneController2.text = '';
                          provider.getHouseLayouts(
                            accessToken: Robot.accessToken,
                            userId: Robot.userId,
                            companyId: Robot.companyId,
                          );
                        },
                        text: "重置",
                        width: 148 / ratio,
                      ),
                    ],
                  ),
                ],
              ),
              SizedBox(width: 40 / ratio),
              Container(
                width: 2.0 / ratio, // The width of the line
                height: 120 / ratio, // The height of the line
                color: Colors.black38, // The color of the line
              ),
              SizedBox(width: 40 / ratio),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 30 / ratio,
                children: [
                  Row(
                    children: [
                      Text(
                        "客户手机",
                        style: TextStyle(
                          color: MyBlack,
                          fontSize: 24 / ratio,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(width: 25 / ratio),
                      SizedBox(
                        width: 374 / ratio,
                        height: 50 / ratio,
                        child: RobotEditText(
                          keyboardType:TextInputType.number,
                          controller: provider.textEditingController,
                          onTextChanged: (text) {
                            provider.setShow(text.isNotEmpty);
                            provider.setPhoneNumber(text);
                          },
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      SizedBox(width: 330/ratio),
                      ConfirmButton(
                        onClick: (text) {
                          if(provider.textEditingController.text.isEmpty){
                            Fluttertoast.showToast(
                                msg: "请输入客户手机",
                                toastLength: Toast.LENGTH_SHORT,
                                timeInSecForIosWeb: 1,
                                fontSize: 16.0
                            );
                            return;
                          }
                          provider.searchByPhone(
                            accessToken: Robot.accessToken,
                            userId: Robot.userId,
                            companyId: Robot.companyId,
                          );
                        },
                        text: "查询",
                        width: 148 / ratio,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}

class Content extends StatelessWidget {
  const Content({super.key});

  @override
  Widget build(BuildContext context) {
    final customerList = context.watch<HuXingProvider>().houseLayoutList;
    final show = context.watch<HuXingProvider>().show;
    return RobotCard(
      child: Padding(
        padding: EdgeInsets.all(30 / ratio),
        child: Stack(
          children: [
            Column(
              children: [
                Info(),
                SizedBox(height: 30 / ratio),
                Expanded(
                  // height: 235,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.0 / ratio),
                    // 保持 CustomScrollView 圆角一致
                    child: CustomScrollView(
                      physics: BouncingScrollPhysics(),
                      slivers: [
                        SliverGrid(
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 7,
                            crossAxisSpacing: 20 / ratio,
                            mainAxisSpacing: 36 / ratio,
                            childAspectRatio:
                                240 /
                                338, // Adjust aspect ratio to control item height
                          ),
                          delegate: SliverChildBuilderDelegate((
                            context,
                            index,
                          ) {
                            return LayoutBuilder(
                              builder: (
                                BuildContext context,
                                BoxConstraints constraints,
                              ) {
                                return Item(
                                  index: index,
                                  constraints: constraints,
                                  houseLayoutItem: customerList[index],
                                );
                              },
                            );
                          }, childCount: customerList.length),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
           if(show)
             ///default a GestureDetector with an invisible child ignores touches; this behavior can be controlled with behavior.
             GestureDetector(
               behavior: HitTestBehavior.translucent,
                 onTap: (){
                   print("onTap");
                   final provider = Provider.of<HuXingProvider>(context, listen: false);
                   provider.setShow(false);
                 },
                 child:
             ConstrainedBox(
               constraints: BoxConstraints.expand(),
               child: Stack(children: [Positioned(
                   right: 0/ratio,
                    top:58/ratio,
                   child: PhoneNumberList()
               )
               ],
               ),
              // PhoneNumberList()
           )
             ),
          ],
        ),
      ),
    );
  }
}

String parseHouseType(String? houseType) {
  if (houseType == null) {
    return '';
  }
  // Regular expression to match X房Y厅 pattern
  final regex = RegExp(r'(\d+)R(\d+)H');

  // Match the input string with the regular expression
  final match = regex.firstMatch(houseType);

  // If a match is found, extract the groups and format the result
  if (match != null) {
    final rooms = match.group(1);
    final halls = match.group(2);
    return '${rooms}房${halls}厅';
  } else {
    return '';
  }
}

class BottomBar extends StatelessWidget {
  const BottomBar({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<HuXingProvider>(
      builder: (context, provider, child) {
        return Container(
          width: double.infinity,
          color: Colors.white,
          height: 84.0 / ratio, // Set row height
          child: Row(
            spacing: 30 / ratio,
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              CancelButton(),
              ConfirmButton(
                text: "户型数据",
                enable: provider.enable1,
                onClick: (text) {
                  provider.onClick1();
                  // provider.setEnable2(true);
                },
              ),
              ConfirmButton(
                text: "识别",
                enable: provider.enable2,
                onClick: (text) {
                  provider.onClick2();
                  // provider.setEnable1(true);
                },
              ),
              SizedBox(width: 30 / ratio),
            ],
          ),
        );
      },
    );
  }
}

class Item extends StatelessWidget {
  final BoxConstraints constraints;
  final int index;
  final HouseLayoutItem houseLayoutItem;

  const Item({
    super.key,
    required this.constraints,
    required this.houseLayoutItem,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<HuXingProvider>(
      builder: (context, provider, child) {
        return GestureDetector(
          onTap: () {
            provider.setIndex(index);
          },
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: MyBlack.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(
                    14 / ratio,
                  ), // Set corner radius
                ),
                child: Center(
                  child: Column(
                    spacing: 0,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(14.0 / ratio),
                        child: Container(
                          color: MyBlack.withOpacity(0.10),
                          // color: Colors.teal,
                          width: constraints.maxWidth,
                          height: constraints.maxWidth,
                          child: Image.network(
                            houseLayoutItem.pictureUrl,
                            fit: BoxFit.contain, // 图片会自动缩放并填满容器
                          ),
                        ),
                      ),
                      SizedBox(height: 10 / ratio),

                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 20 / ratio),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              houseLayoutItem.name.toString(),
                              style: TextStyle(
                                fontSize: 24 / ratio,
                                color: MyBlack,
                                letterSpacing: 0,
                                wordSpacing: 0,
                              ),
                            ),
                            SizedBox(height: 10 / ratio),
                            Row(
                              children: [
                                Text(
                                  parseHouseType(houseLayoutItem.houseType),
                                  style: TextStyle(
                                    fontSize: 24 / ratio,
                                    color: MyBlack.withOpacity(0.60),
                                    letterSpacing: 0,
                                    wordSpacing: 0,
                                  ),
                                ),
                                Spacer(),
                                Text(
                                  "${houseLayoutItem.innerArea}㎡",
                                  style: TextStyle(
                                    fontSize: 24 / ratio,
                                    color: MyBlack.withOpacity(0.60),
                                    letterSpacing: 0,
                                    wordSpacing: 0,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                top: 44 / ratio,
                right: 21 / ratio,
                child: InteractiveCircle(
                  isClicked: provider.selectedIndex == index,
                ),
              ),
              if (provider.selectedIndex == index)
                Container(
                  decoration: BoxDecoration(
                    color: MyBLUE.withOpacity(0.40),
                    borderRadius: BorderRadius.circular(
                      14 / ratio,
                    ), // Set corner radius
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}

class InteractiveCircle extends StatelessWidget {
  final bool isClicked;

  const InteractiveCircle({super.key, required this.isClicked});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 30 / ratio, // Diameter of the circle
      height: 30 / ratio,
      decoration: BoxDecoration(
        color:
            isClicked
                ? Colors
                    .blue // Blue background when clicked
                : Colors.white.withOpacity(0.6), // Default transparent white
        shape: BoxShape.circle,
      ),
      child:
          isClicked
              ? Icon(
                Icons.check, // Checkmark icon
                color: Colors.white,
                size: 30 / ratio, // Icon size
              )
              : null, // No icon when not clicked
    );
  }
}

class PhoneNumberList extends StatelessWidget {
  const PhoneNumberList({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<HuXingProvider>(
      builder: (context, provider, child) {
        print("PhoneList  builder");
        return Container(
          color: Colors.white.withOpacity(1.0),
          // height: 200,
          width: 374 / ratio,
          child: Column(
            children: List.generate(
              provider.filteredList.length,
              (index) => ClickableContainer(text1:provider.phoneNumber,text2: provider.filteredList[index],onTap: (text){
                provider.setTextFieldValue(text.split(' ')[0]);
                provider.setShow(false);
                // phoneController8
                // provider.setPhoneNumber(text.split(' ')[0]);
              },),
            ),
          ),
        );
      },
    );
  }
}

class ClickableContainer extends StatefulWidget {
  final String text1;
  final String text2;
  // 定义变量为一个函数，参数是 String 类型
  final Function(String) onTap;


  const ClickableContainer({super.key, required this.text1, required this.text2, required this.onTap});

  @override
  _ClickableContainerState createState() => _ClickableContainerState();
}

class _ClickableContainerState extends State<ClickableContainer> {
  bool _isPressed = false;

  @override
  Widget build(BuildContext context) {
    final String text1 =widget.text1;
    final String text2 = widget.text2;
    String result = text2.startsWith(text1) ? text2.replaceFirst(text1, '') : text2;
    return GestureDetector(
      onTap: (){
        widget.onTap(widget.text2);
      },
      onTapDown: (_) {
        setState(() {
          _isPressed = true;
        });
      },
      onTapUp: (_) {
        setState(() {
          _isPressed = false;
        });
      },
      onTapCancel: () {
        setState(() {
          _isPressed = false;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20/ratio),
        color: _isPressed ? Colors.grey[300] : Colors.white,
        height: 80 / ratio,
        width: 374/ratio,
          alignment: Alignment.centerLeft,
          child: Text.rich(
            maxLines: 1,
            overflow: TextOverflow.ellipsis, // Adds '...' when the text exceeds one line
            TextSpan(
              children: [
                TextSpan(text: widget.text1, style: TextStyle(color: MyBLUE,fontSize:24/ratio)),
                TextSpan(text: result, style: TextStyle(color: MyBlack,fontSize:24/ratio)),
              ],
            ),
          ),
      ),
    );
  }
}



class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // Register to observe lifecycle changes
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // Unregister observer when widget is disposed
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("didChangeAppLifecycleState"+state.name);
    if (state == AppLifecycleState.resumed) {
      // This is called when the app comes to the foreground
      Provider.of<HuXingProvider2>(context, listen: false).resetVariable();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<HuXingProvider2>(
      builder: (context, provider, child) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Your App'),
          ),
          body: Center(
            child: Text('Your value: ${provider.variable}'),
          ),
        );
      },
    );
  }
}

class HuXingProvider2 with ChangeNotifier {
  String _variable = 'Initial Value';

  String get variable => _variable;

  void resetVariable() {
    _variable = 'Reset Value'; // Reset the variable when needed
    notifyListeners(); // Notify listeners to update UI
  }
}

